package com.example.lirisheng.springbootfinalexperiment.security.filter;

import com.example.lirisheng.springbootfinalexperiment.util.JSON;
import com.example.lirisheng.springbootfinalexperiment.util.RespBean;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 腾讯验证码验证的filter
 */
@Component
public class AdminCaptcharFilter extends OncePerRequestFilter {
    private static final String DEFAULT_FILTER_RUL="/adminLogin";
    private static final String  DEFAULT_INCORRECT_RUL = "/admin/incorrectCap";
    private static final String   appId="2056622217";
    private static final String   appScretKey="0ZcOrzZiYlRhqsNrc8Bzrlg**";
    private static final String   secretId="AKIDFG1TdIRScXMwKQp7fvusZ2CRCgCb7qFP";
    private static final String   secretKey="FBuNwOKvHQJxIhALGt1pMcUDcRzGI3Y0";
    private static final String   DEFAULT_AUTHENTICATEDCAPTCHA_RUL="captcha.tencentcloudapi.com";
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //拦截/adminLogin
        if(!httpServletRequest.getRequestURI().endsWith(DEFAULT_FILTER_RUL)||!"POST".equals(httpServletRequest.getMethod())){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        String ticket=httpServletRequest.getParameter("ticket");
//               Assert.notNull(ticket,"ticket不能为空");
        String randstr = httpServletRequest.getParameter("randstr");
//               Assert.notNull(randstr,"Rnadstr不能为空");

        try{

            Credential cred = new Credential(secretId, secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(DEFAULT_AUTHENTICATEDCAPTCHA_RUL);

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CaptchaClient client = new CaptchaClient(cred, "", clientProfile);

            String params = "{Action:DescribeCaptchaResult,CaptchaType=9,Ticket="+ticket+",UserIp=127.0.0.1 ,Randstr="+randstr+",CaptchaAppId="+appId+",AppSecretKey="+appScretKey+",NeedGetCaptchaTime=1}";
            DescribeCaptchaResultRequest req = DescribeCaptchaResultRequest.fromJsonString(params, DescribeCaptchaResultRequest.class);

            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);

            System.out.println(DescribeCaptchaResultRequest.toJsonString(resp));
            if(logger.isDebugEnabled()){
                logger.debug(DescribeCaptchaResultRequest.toJsonString(resp));
            }
            Long status=resp.getCaptchaCode();
            if(logger.isDebugEnabled()){
                logger.debug("验证后的状态:"+status);
                logger.debug("错误码:"+resp.getCaptchaCode());
                logger.debug("错误信息:"+resp.getCaptchaMsg());
            }
            if(status==1){
                if(logger.isDebugEnabled()){
                    logger.debug("验证通过");
                }
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }

            if(logger.isDebugEnabled()){
                logger.debug("腾讯验证码验证不通过");
            }

            //返回json数据给前端
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.getWriter().write(JSON.writeValue(RespBean.error("腾讯验证码验证不通过")));
            return;

        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            if(logger.isDebugEnabled()){
                logger.debug("腾讯验证码验证过程中抛出异常");
            }

            //返回json数据给前端
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.getWriter().write(JSON.writeValue(RespBean.error("验证不通过")));
            return;
        }
    }
}